<template>
  <div style="height: 100%">
    <el-link
      type="warning"
      class="ml20 record"
      :underline="false"
      @click="viewChangeRecord"
      >变更记录</el-link
    >
    <el-button type="primary" @click="handleMultipleSet" :disabled="loading"
      >已勾选{{ checkedKeys.length }}条，批量操作</el-button
    >
    <div class="tree">
      <el-tree
        v-loading="loading"
        ref="treeRefs"
        show-checkbox
        node-key="id"
        :data="treeData"
        :props="defaultProps"
        @check-change="onCheckChange"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="label">{{ node.label }}</span>
          <span class="tree-node-append" v-if="node.isLeaf">
            <el-input-number
              :disabled="!checkedKeys.includes(data.id)"
              size="mini"
              v-model="data.servicePrice"
              controls-position="none"
              :controls="false"
              @change="onInputChange"
              :min="0"
              :max="99999"
            ></el-input-number>
            &nbsp;&nbsp; {{ serviceUnit }}
          </span>
        </span>
      </el-tree>
    </div>
    <el-button
      style="margin: 10px 46%"
      type="primary"
      @click="submit"
      :disabled="loading"
      :loading="saveLoading"
      >保存</el-button
    >
    <SetAllPrice
      ref="setAllPriceRefs"
      @multipleSubmit="(e) => submit(e, 'multiple')"
    />
    <el-dialog :visible.sync="changeRecordVisible" title="变更记录">
      <div>类目：{{ categoryName }}</div>
      <ul class="infinite-list" v-infinite-scroll="load" style="overflow: auto">
        <div v-for="i in changeRecords" :key="i.id" class="infinite-list-item">
          <div>
            <span>{{ i.changeTime }}</span>
            <span class="ml10 mr10">{{ i.changeUserName }}</span>
          </div>
          <div>
            <div
              v-for="item in i.changeShowText.split(',')"
              :key="item"
              class="ml10 mb10"
            >
              <el-link type="info" :underline="false"> {{ item }}</el-link>
            </div>
          </div>
        </div>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiGetSysDistrictTreeWithServiceQuotation,
  apiServiceQuotationInsertOrUpdateBatch,
  apiSaasServiceInsertOrUpdateBatch,
  apiGetSysDistrictTreeWithSaasService,
  apiPriceChangeRecordGetPriceChangeRecordPage,
} from "@/api/serviceClassify.js";
import SetAllPrice from "./setAllPrice.vue";
export default {
  components: { SetAllPrice },
  props: {
    categoryId: {
      type: String,
      default: "",
    },
    categoryName: {
      type: String,
      default: "",
    },
    serviceUnit: {
      type: String,
      default: "",
    },
    serviceId: {
      type: String,
      default: "",
    },
    saasId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      treeData: [],
      loading: false,
      saveLoading: false,
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: "leaf",
      },
      changeRecordVisible: false,
      changeRecords: [],
      pageNum: 1,
      pageSize: 20,
      pageTotal: 1,
    };
  },
  mounted() {
    this.loadNode();
  },
  methods: {
    submit(values, type) {
      const checkedNodes = this.$refs.treeRefs.getCheckedNodes(true);
      if (checkedNodes.length == 0) {
        this.$message({ type: "warning", message: "请选择服务区域" });
        return false;
      }
      let error = [];

      const list = checkedNodes.map((item) => {
        if (!item.servicePrice) {
          console.log(item, "aaas");
          error.push(item.name);
        }
        const obj = {
          district: item.name,
          districtId: item.id,
          servicePrice:
            type == "multiple"
              ? values.servicePrice * 100
              : item.servicePrice * 100,
          serviceId: this.serviceId,
          serviceCategoryId: this.categoryId,
          id: item.serviceQuotationResDTOId,
        };
        if (this.saasId) {
          obj.saasId = this.saasId;
          obj.id = item.saasServiceResDTOId;
        }
        return obj;
      });
      if (error && error.length > 0 && !type) {
        console.log(error);
        this.$message({ type: "warning", message: error[0] + "未设置价格" });
        return false;
      }

      this.saveLoading = true;
      if (this.saasId) {
        //修改服务商价格
        apiSaasServiceInsertOrUpdateBatch(list)
          .then((res) => {
            this.checkedKeys = [];
            this.loadNode();
            this.$message({ type: "success", message: "保存成功" });
            this.saveLoading = false;
          })
          .catch((err) => {
            this.saveLoading = false;
          });
      } else {
        apiServiceQuotationInsertOrUpdateBatch(list)
          .then((res) => {
            this.checkedKeys = [];
            this.loadNode();
            this.$message({ type: "success", message: "保存成功" });
            this.saveLoading = false;
          })
          .catch((err) => {
            this.saveLoading = false;
          });
      }
    },
    guideData(data) {
      console.log(data, "aaaaaa");
      const res = data.map((item) => {
        if (
          item.hasOwnProperty("children") &&
          item.children &&
          item.children.length > 0 &&
          item.level != "area"
        ) {
          item.children = this.guideData(item.children);
        } else {
          if (this.saasId) {
            if (
              item.hasOwnProperty("saasServiceResDTO") &&
              item.saasServiceResDTO
            ) {
              item = {
                ...item,
                servicePrice: item.saasServiceResDTO.servicePrice / 100,
                saasServiceResDTOId: item.saasServiceResDTO.id,
              };
            } else {
              item = {
                ...item,
                servicePrice: undefined,
                saasServiceResDTOId: null,
              };
            }
          } else {
            if (
              item.hasOwnProperty("serviceQuotationResDTO") &&
              item.serviceQuotationResDTO
            ) {
              item = {
                ...item,
                servicePrice: item.serviceQuotationResDTO.servicePrice / 100,
                serviceQuotationResDTOId: item.serviceQuotationResDTO.id,
              };
            } else {
              item = {
                ...item,
                servicePrice: undefined,
                serviceQuotationResDTOId: null,
              };
            }
          }
        }
        return item;
      });
      console.log(res, "aaaa");
      return res;
    },
    onCheckChange(e, a, v) {
      this.checkedKeys = this.$refs.treeRefs.getCheckedKeys(true);
    },
    handleMultipleSet() {
      if (this.checkedKeys.length == 0) {
        this.$message({ type: "warning", message: "请选择服务区域" });
        return false;
      }
      const checkedKeys = this.$refs.treeRefs.getCheckedKeys(true);
      this.$refs.setAllPriceRefs.open();
    },
    onInputChange() {
      const checkedNodes = this.$refs.treeRefs.getCheckedNodes(true);
      console.log(checkedNodes);
    },
    viewChangeRecord() {
      this.pageNum = 1;
      this.changeRecords = [];
      this.changeRecordVisible = true;
      this.$nextTick(() => {
        this.load();
      });
    },
    load() {
      if (this.pageNum > this.pageTotal) return false;
      apiPriceChangeRecordGetPriceChangeRecordPage({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        serviceId: this.serviceId,
      }).then((res) => {
        this.changeRecords = this.changeRecords.concat(...res.data);
        this.pageNum += 1;
        this.pageTotal = res.pages;
      });
    },
    async loadNode(node, resolve) {
      this.loading = true;
      this.treeData = [];
      if (this.saasId) {
        //saas服务商
        apiGetSysDistrictTreeWithSaasService({
          saasId: this.saasId,
          serviceId: this.serviceId,
        })
          .then((res) => {
            this.loading = false;
            this.treeData = this.guideData(
              res.data.filter((item) => item.level == "province")
            );
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        //平台
        apiGetSysDistrictTreeWithServiceQuotation({
          serviceId: this.serviceId,
        })
          .then((res) => {
            this.loading = false;
            this.treeData = this.guideData(
              res.data.filter((item) => item.level == "province")
            );
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    getDistrict(pid) {
      return new Promise((resolve, reject) => {});
    },
  },
};
</script>

<style scoped lang="scss">
.label {
  display: inline-block;
  width: 150px;
}
.tree-node-append {
  display: inline-block;
  width: 200px;
  text-align: left;
}
::v-deep .el-tree-node__content {
  height: 40px;
}
.tree {
  height: calc(100% - 80px);
  overflow: auto;
}
.infinite-list {
  height: 600px;
}
.record {
  position: absolute;
  right: 40px;
  top: 20px;
}
.infinite-list-item {
  display: flex;
  flex-wrap: wrap;
}
</style>
